// import OSS from 'ali-oss'
import crypto from './crypto-js'
// const app = getApp()
import {
  Base64
} from './base64.min.js';
let tokenCons = {}
let isToken = false
const statusObj = {
  400: '请求错误',
  401: '未授权，请登录',
  403: '拒绝访问',
  404: `请求地址出错`,
  408: '请求超时',
  500: '服务器开个小差，请稍后再试',
  501: '服务器开个小差，请稍后再试',
  502: '服务器开个小差，请稍后再试',
  503: '服务器开个小差，请稍后再试',
  504: '服务器开个小差，请稍后再试',
  505: 'HTTP版本不受支持'
}
const requestUploadParams = {
  region: '', //服务器区域 如：oss-cn-beijing
  bucket: '', //桶名 
  domain: '' //域名
}
let computeSignature = function (accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));

}
let getFormDataParams = async function (file, name) {
    let res = await uploadOSSToken()
    const date = new Date();
    date.setHours(date.getHours() + 1);
    const policyText = {
      expiration: date.toISOString(), // 设置policy过期时间。
      conditions: [
        ["content-length-range", 0, 1024 * 1024 * 5],
      ]
    }
    const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    const signature = computeSignature(res.AccessKeySecret, policy)
    console.log(file, 'file------')
    let suffix = file
    const uploadPath = + name + '/' + res.date_dir + '/' + randomString(6) + suffix
    const formData = {
      OSSAccessKeyId: res.AccessKeyId,
      signature,
      policy,
      'x-oss-security-token': res.SecurityToken,
      key: uploadPath
    }
    return formData
  },
  getToken = function(){
    return new Promise(function (resolve) {
      isToken = true
      uni.request({
        method: 'get',
        url: '',//阿里云域名接口如：https://file-hs.us0.m
        complete: (res) => {
          isToken = false
          if (res.statusCode === 200) {
            res.data.code === 200 ? resolve(res.data.data) : uni.showToast({
              title: res.data.msg
            })
            // app.globalData.outTime = Date.now()+10*60*1000
          } else {
          }
          console.log(res, '==')
          resolve(res)
        },
        fail(error) {
        }
      })
    })
  },
  uploadOSSToken = function () {
    // console.log(app.globalData.outTime,'app.globalData.outTime-----')
    return new Promise ( async function  (resolve) {
		// (!app.globalData.outTime || Date.now() >= app.globalData.outTime )&& 
      if (!isToken) {
        tokenCons =  await getToken()
      }
      resolve(tokenCons)
    })
  },
  randomString = function (e) {
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
      a = t.length,
      n = "";
    for (var i = 0; i < e; i++) {
      n += t.charAt(Math.floor(Math.random() * a))
    }
    return n + Date.now()
  },
  uploadOss = async (path, file, packageName) => {
    return new Promise(async (resolve) => {
      try {
        let formData = await getFormDataParams(file, packageName)
        uni.uploadFile({
          url: '',//接口域名
          name: 'file',
          formData: formData,
          filePath: path,
          success: (uploadFileRes) => {
            if (uploadFileRes.statusCode === 204) {
              resolve({
                code: 200,
                data: {
                  url: requestUploadParams.domain + '/' + formData.key
                }
              })
            } else {
              resolve({
                code: 101
              })

            }
          }
        })
      } catch (error) {
        console.log(error, '-----error')
        resolve({
          code: 101
        })

      }
    })
  }
module.exports = {
  uploadOss
}